package com.skynet.app.api.auth.filter;

import lombok.extern.slf4j.Slf4j;

import com.skynet.app.api.auth.enums.ResultEnum;
import com.skynet.app.api.auth.util.JwtTokenUtil;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@Slf4j
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String header = request.getHeader("Authorization");

        if (header != null && header.startsWith("Bearer ")) {
            UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        chain.doFilter(request, response);
    }

    private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Claims claims = JwtTokenUtil.parseToken(token);
        if (claims == null) {
            log.error("【用户鉴权】鉴权失败，reason={}", ResultEnum.TOKEN_PARSE_ERROR.getMsg());
            return null;
        }
        String email = String.valueOf(claims.get("email"));
        log.info("【用户鉴权】email={}", email);
        return new UsernamePasswordAuthenticationToken(email, null, new ArrayList<>());
    }
}
